package com.guchenbo.tomcat;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;

public class DemoHttpClient {
    protected static final Logger log = LoggerFactory.getLogger(DemoHttpClient.class);

    private static RestTemplate restTemplate = new RestTemplate();
    private static String url = "http://localhost:8080/reqResServlet?a=1&b=2";

    public static void main(String[] args) {
        postParam();
        postBody();
    }

    private static void postBody() {
        User user = new User();
        user.setName("jay");
        user.setAge(18);
        String body = JSON.toJSONString(user);
        File dest = new File("/Users/guchenbo/Downloads/demo.png");
        restTemplate.execute(URI.create(url), HttpMethod.POST, restTemplate.httpEntityCallback(body), response -> {
            handleStream(response.getBody(), new FileOutputStream(dest));
            return null;
        });
    }

    private static void postParam() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("fk1", "fv1");
        map.add("fk2", "fv2");

        restTemplate.execute(URI.create(url), HttpMethod.POST, restTemplate.httpEntityCallback(map), response -> null);
    }

    public static final int BUFFER_SIZE = 4096;

    public static void handleStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        if (inputStream == null) {
            return;
        }
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            // handle bytes
            log.info("#########读取就处理######## bytes: {}", bytesRead);
            outputStream.write(buffer);
        }
        outputStream.flush();
    }
}
